"""add user_preferences table"""

from alembic import op
import sqlalchemy as sa


revision = "202510180001"
down_revision = "202510170002"
branch_labels = None
depends_on = None


def upgrade() -> None:
  op.create_table(
    "user_preferences",
    sa.Column("id", sa.Integer(), primary_key=True, index=True),
    sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
    sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
    sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
    sa.Column("user_id", sa.Integer(), nullable=False),
    sa.Column("relationship_id", sa.Integer(), nullable=True),
    # MySQL 不允许为 JSON/TEXT/BLOB 设置默认值，移除 server_default
    sa.Column("data_json", sa.JSON(), nullable=False),
    sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
    sa.ForeignKeyConstraint(["relationship_id"], ["relationships.id"], ondelete="SET NULL"),
    sa.UniqueConstraint("user_id", "relationship_id", name="uq_user_pref_user_rel"),
  )
  op.create_index("ix_user_preferences_user_id", "user_preferences", ["user_id"], unique=False)
  op.create_index("ix_user_preferences_relationship_id", "user_preferences", ["relationship_id"], unique=False)


def downgrade() -> None:
  op.drop_index("ix_user_preferences_relationship_id", table_name="user_preferences")
  op.drop_index("ix_user_preferences_user_id", table_name="user_preferences")
  op.drop_table("user_preferences")
